package com.ideal.manage.esms.service.alarm;

import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.diagnostic.DiagnoseResultInfo;
import com.ideal.manage.esms.bean.alarm.Threshold;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.bean.project.ProjectManage;
import com.ideal.manage.esms.bean.project.ThresholdManage;
import com.ideal.manage.esms.bean.sys.User;
import com.ideal.manage.esms.config.shiro.MyShiroRealm;
import com.ideal.manage.esms.repository.diagnostic.DiagnoseResultInfoRepository;
import com.ideal.manage.esms.repository.alarm.AlarmThresholdRepository;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.ThresholdManageRepository;
import com.ideal.manage.esms.repository.system.UserProjectRepository;
import com.ideal.manage.esms.repository.system.UserRepository;
import com.ideal.manage.esms.util.HttpRequests;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class AlarmThresholdService {

    @Autowired
    private EquipmentManageRepository equipmentManageRepository;
    @Autowired
    private UserProjectRepository userProjectRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ThresholdManageRepository thresholdManageRepository;
    @Autowired
    private AlarmThresholdRepository alarmThresholdRepository;
    @Autowired
    private DiagnoseResultInfoRepository diagnoseResultInfoRepository;


    /**
     * @param name
     * @return 树信息
     */
    public List<JSONObject> getProjectAndEquipment(String name) {
        List<JSONObject> list = new ArrayList<>();
        // 将所有的项目加入list
        List<ProjectManage> projectManageList = new ArrayList<ProjectManage>();
        //获取当前登录用户
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = userRepository.findOne(shiroUser.getId());
        if (StringUtils.isBlank(name)) {
            projectManageList = userProjectRepository.findProjectByUser(user);
        } else {
            projectManageList = userProjectRepository.findProjectByUserAndName(user, name);
        }
        if (projectManageList.size() < 1) {
            return null;
        }
        projectManageList.forEach(projectManage -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", projectManage.getId());
            jsonObject.put("pId", 0L);
            jsonObject.put("name", projectManage.getName());
            jsonObject.put("type", 0L);
            list.add(jsonObject);
        });
        // 将所有的设备放到list
        List<EquipmentManage> equipmentManageList = equipmentManageRepository.findByProjects(projectManageList);
        equipmentManageList.forEach(equipmentManage -> {
            if (Integer.valueOf(equipmentManage.getEquipmentType()) > 2) {
                return;
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", equipmentManage.getId());
                if (equipmentManage.getParent() == null) {
                    jsonObject.put("pId", equipmentManage.getProject().getId());
                } else {
                    jsonObject.put("pId", equipmentManage.getParent().getId());
                }
                jsonObject.put("name", equipmentManage.getName());
                jsonObject.put("type", equipmentManage.getEquipmentType());
                list.add(jsonObject);
            }
        });
        return list;
    }

    //入库判断
    public String getThresholdAndEquipment(String id, String pId) {
        List<Threshold> lists = alarmThresholdRepository.findByAlarmThresholdIds();
        for (Threshold threshold : lists) {
            String thresholdId = threshold.getEquipmentManage().getId();
            if (thresholdId.equals(id)) {
                return null;
            }
        }

        Threshold manage = new Threshold();
        int objName = 0;
        String thName = "";
        Map<String, Integer> equipmentValue = new HashMap<>();
        //1.查询相对应的设备
        EquipmentManage equipmentData = equipmentManageRepository.findOne(id);
        if (equipmentData == null) {
            return null;
        }
        //取出设备的名称,设备的类型
        equipmentValue.put(equipmentData.getName(), Integer.parseInt(equipmentData.getEquipmentType()));
        for (Map.Entry<String, Integer> entry : equipmentValue.entrySet()) {
            objName = entry.getValue();
        }
        //2.查询相对应的阈值管理信息
        List<ThresholdManage> allThresholdData = thresholdManageRepository.findThresholdManages();
        for (ThresholdManage thresholdManage : allThresholdData) {
            if (objName == thresholdManage.getObjName()) {
                //UUID
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                manage.setId(uuid);
                //入库设备id
                EquipmentManage equipmentManage = new EquipmentManage();
                equipmentManage.setId(id);
                manage.setEquipmentManage(equipmentManage);
                //项目id
                ProjectManage projectManage = new ProjectManage();
                projectManage.setId(pId);
                manage.setProjectManage(projectManage);
                //获取阈值管理表的id
                String tId = thresholdManage.getId();
                ThresholdManage tM = new ThresholdManage();
                tM.setId(tId);
                manage.setThresholdManage(tM);
                //阈值名称
                thName = thresholdManage.getName();
                manage.setThresholdName(thName);
                //设定值
                String val = thresholdManage.getSysDefVal();
                String unit = thresholdManage.getUnit();
                String setVal = val + unit;
                manage.setSetVal(setVal);
                //诊断分析结果数值
                List<DiagnoseResultInfo> diagnoses = diagnoseResultInfoRepository.findDiagnoses();
                for (DiagnoseResultInfo Dinfo : diagnoses) {

                    if (Dinfo.getEquipment() == null) {
                        continue;
                    } else if (Dinfo.getEquipment().getId() == id) {
                        manage.setSuggestVal(Dinfo.getResultVal());// 这里需要诊断分析中数据结果表中的返回值
                        break;
                    } else {
                        manage.setSuggestVal("");
                    }
                }
                //获取阈值管理表的修改时间
                if (thresholdManage.getUpdateTime() == null) {
                    manage.setUpdateTime(new Date());
                }
                manage.setUpdateTime(thresholdManage.getUpdateTime());
                manage.setCreateTime(new Date());
                manage.setIsValid(1);
                alarmThresholdRepository.save(manage);
            }
        }
        return "";
    }

    /**
     * 查找所有有效信息
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findThresholdAllData(int pageNum, HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(isValid);
        MySpecification<Threshold> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<Threshold> page = alarmThresholdRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<Threshold> thresholds = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(thresholds);
        pageDto.setTotal(total);
        return pageDto;


    }

    /**
     * 编辑
     * @param id
     * @return
     */
    public Threshold findThresholdOneData(String id) {
        Threshold one = alarmThresholdRepository.findOne(id);
        return one;
    }

    /**
     * 编辑保存
     * @param id
     * @param setVal
     */
    public void editSave(String id, String setVal) {
        Threshold oneData = alarmThresholdRepository.findOne(id);
        Threshold threshold = new Threshold();
        threshold.setId(id);
        threshold.setProjectManage(oneData.getProjectManage());
        threshold.setEquipmentManage(oneData.getEquipmentManage());
        threshold.setThresholdManage(oneData.getThresholdManage());
        threshold.setThresholdName(oneData.getThresholdName());
        threshold.setSetVal(setVal);
        threshold.setSuggestVal(oneData.getSuggestVal());
        threshold.setUpdateTime(oneData.getUpdateTime());
        threshold.setCreateTime(oneData.getCreateTime());
        threshold.setIsValid(oneData.getIsValid());
        alarmThresholdRepository.save(threshold);
    }

    /**
     * 重置
     * @param id
     */
    public void resetValue(String id) {
        Threshold oneData = alarmThresholdRepository.findOne(id);
        ThresholdManage manage = oneData.getThresholdManage();
        String tId = manage.getId();
        ThresholdManage tMdata = thresholdManageRepository.findOne(tId);
        String sysDefVal = tMdata.getSysDefVal();
        String unit = tMdata.getUnit();
        String setVal = sysDefVal + unit;
        //入库
        Threshold threshold = new Threshold();
        threshold.setId(id);
        threshold.setProjectManage(oneData.getProjectManage());
        threshold.setEquipmentManage(oneData.getEquipmentManage());
        threshold.setThresholdManage(oneData.getThresholdManage());
        threshold.setThresholdName(oneData.getThresholdName());
        threshold.setSetVal(setVal);
        threshold.setSuggestVal(oneData.getSuggestVal());
        threshold.setUpdateTime(oneData.getUpdateTime());
        threshold.setCreateTime(oneData.getCreateTime());
        threshold.setIsValid(oneData.getIsValid());
        alarmThresholdRepository.save(threshold);
    }

    /**
     * 口令校验
     * @param changePassword
     */
    public List<User> findByChanPwd(String changePassword) {

      return  userRepository.findByChangePassword(changePassword);
    }
}
